package cn.easybuy.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.easybuy.biz.Easybuy_Newsbiz;
import cn.easybuy.biz.Impl.Easybuy_NewsbizImpl;
import cn.easybuy.entity.Easybuy_News;
import cn.easybuy.util.Page;

public class Newsfy extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		List<Easybuy_News> list = new ArrayList<Easybuy_News>();
		PrintWriter out = response.getWriter();
		Easybuy_Newsbiz ea = new Easybuy_NewsbizImpl();
		Page page = new Page();
		String idd = request.getParameter("id");
		if (idd == null) {
			String pageIndex = request.getParameter("pageIndex");
			if (pageIndex == null) {
				pageIndex = "1";
			}
			int pageindex = Integer.parseInt(pageIndex);
			int totalCount = 0;
			totalCount = ea.getTotalCount();
			page.setPageSize(10);
			page.setTotalCount(totalCount);
			int totalPages = page.getTotalpagecount();
			int currPageNo = pageindex;
			page.setCurrPageNo(currPageNo);
			if (pageindex > totalPages) {
				pageindex = totalPages;
			}
			if (pageindex < 1) {
				pageindex = 1;

			}
			int i = 0;
			list = ea
					.getAllnewsByPage(page.getCurrPageNo(), page.getPageSize());
			page.setNewsList(list);
			String newsJSON = JSON.toJSONString(page,
					SerializerFeature.WriteMapNullValue,
					SerializerFeature.WriteNullNumberAsZero,
					SerializerFeature.WriteNullStringAsEmpty);
			out.print(newsJSON);
			out.flush();
			out.close();
		} else if (idd != null) {
			String id = request.getParameter("id");

			list = ea.findAllNewsByTid(Integer.parseInt(id));
			String newsJSON = JSON.toJSONString(list,
					SerializerFeature.WriteMapNullValue,
					SerializerFeature.WriteNullNumberAsZero,
					SerializerFeature.WriteNullStringAsEmpty);
			out.print(newsJSON);
			out.flush();
			out.close();
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}
